package com.example.service.utils;

import com.example.constants.PathConstants;
import com.example.entity.drugDTO.DrugMatchingRequest;
import org.json.JSONObject;
import org.json.JSONException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Python脚本执行工具类
 */
public class PythonExecuteUtil {

    /**
     * 执行药品推荐脚本
     * @param request 药品推荐请求对象
     * @return 推荐的药品名称
     */
    public static String executeDrugMatching(DrugMatchingRequest request) {
        List<String> command = new ArrayList<>();
        command.add("python");
        command.add(PathConstants.PYTHON_PATH.concat("drug_recommendation.py"));

        // 添加脚本参数
        command.add("--gender");
        command.add(request.getGender());
        command.add("--age");
        command.add(String.valueOf(request.getAge()));
        command.add("--symptom");
        command.add(request.getSymptom());
        command.add("--allergy");
        command.add(request.getAllergy());
        command.add("--temperature");
        command.add(String.valueOf(request.getTemperature()));

        ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectErrorStream(true);  // 合并错误流到标准输出
        Process process = null;

        try {
            process = builder.start();
            String jsonOutput = readProcessOutput(process);
            return parseJsonResult(jsonOutput, "medicine");
        } catch (Exception e) {
            throw new RuntimeException("执行药品推荐脚本失败: " + e.getMessage(), e);
        } finally {
            if (process != null && process.isAlive()) {
                process.destroy();  // 确保进程被销毁
            }
        }
    }

    /**
     * 强制重新训练模型
     * @return 训练结果消息
     */
    /*public static String retrainDrugMatchingModel() {
        List<String> command = new ArrayList<>();
        command.add("python");
        command.add(PathConstants.PYTHON_PATH.concat("drug_recommendation.py"));
        command.add("--retrain");

        ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectErrorStream(true);
        Process process = null;

        try {
            process = builder.start();
            String jsonOutput = readProcessOutput(process);
            return parseJsonResult(jsonOutput, "message");
        } catch (Exception e) {
            throw new RuntimeException("重新训练模型失败: " + e.getMessage(), e);
        } finally {
            if (process != null && process.isAlive()) {
                process.destroy();
            }
        }
    }*/

    /**
     * 读取进程输出并提取JSON结果
     */
    private static String readProcessOutput(Process process)
            throws IOException, InterruptedException {
        //读取Python输出
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream(), "GBK"));
        String line;
        String jsonLine = null;

        // 实时输出Python脚本日志，检测以{开头的行（JSON结果）。
        while ((line = reader.readLine()) != null) {
            System.out.println("[Python输出] " + line);
            if (line.trim().startsWith("{")) {
                jsonLine = line.trim();
            }
        }

        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new RuntimeException("Python脚本异常退出，代码: " + exitCode);
        }

        if (jsonLine == null) {
            throw new RuntimeException("未获取到有效的JSON格式输出");
        }
        return jsonLine;
    }

    /**
     * 解析JSON结果
     */
    private static String parseJsonResult(String jsonLine, String resultKey)
            throws JSONException {
        JSONObject resultJson = new JSONObject(jsonLine);

        if (!"success".equals(resultJson.getString("status"))) {
            throw new RuntimeException("Python脚本执行错误: " +
                    resultJson.optString("message", "未知错误"));
        }
        return resultJson.getString(resultKey);
    }
}
